//
//  HomeViewController.m
//  EasyToTesco
//
//  Created by mc on 16/1/29.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "HomeViewController.h"

#import "HeaderFileForEasyToTesco.h"
#import "SDCycleScrollView.h"
#import "ButtonView.h"
#import "HomeTableViewCell.h"

#import "RecomTableViewCell.h"
#import "UIImageView+WebCache.h"

//其他分类
#import "OtherClassificationViewController.h"
//鞋包服饰
#import "ShoeBagDressViewController.h"
//石油充值
#import "OilChangeViewController.h" //"OilTopupViewController.h"
//话费充值
#import "MoreCreditViewController.h"
//刷新控件头文件
#import "SDRefresh.h"

//评分
#import "CWStarRateView.h"
//二维码扫描页面
#import "ScanViewController.h"

//活动页面
#import "ActivityViewController.h"
//微商专区头文件
#import "DerivativeViewController.h"
#import "GPDateView.h"
//cell点击后的详情页面
//#import "HomecellDetailViewController.h"

#import "ShoperDetailViewController.h"

//数据解析
#import "AFNetworking.h"

//城市列表视图的头文件
#import "CityListViewController.h"
//搜索界面
#import "SearchViewController.h"

#import "ReadLoginData.h"
#define WIDTH [[UIScreen mainScreen] bounds].size.width
#define NORMWIDTH [[UIScreen mainScreen] bounds].size.width / 375
#define HEIGHT [[UIScreen mainScreen] bounds].size.height
#define NORMHEIGHT [[UIScreen mainScreen] bounds].size.height / 667
#define FRAME [[UIScreen mainScreen] bounds]
#define DeviceHeight            [[UIScreen mainScreen] bounds].size.height
#define DeviceWidth             [[UIScreen mainScreen] bounds].size.width
#define Key_DistrictSelectProvince          @"DistrictSelectProvince"
#define Key_DistrictSelectProvinceCode      @"DistrictSelectProvinceCode"
#define Key_DistrictSelectProvinceSubCode   @"DistrictSelectProvinceSubCode"
#define Key_DistrictSelectProvinceSub       @"DistrictSelectProvinceSub"
#define Key_DistrictSelectCityCode          @"DistrictSelectCityCode"
#define Key_DistrictSelectCity              @"DistrictSelectCity"

@interface HomeViewController()<SDCycleScrollViewDelegate, UITableViewDataSource, UITableViewDelegate>

{
    NSMutableArray *SDCycleArray;
    
}
@property (nonatomic, strong)UITableView *HomeTableView;
//刷新控件
@property (nonatomic, weak) SDRefreshFooterView *refreshFooter;
@property (nonatomic, weak) SDRefreshHeaderView *refreshHeader;

//中间的选择区域前面四个和最后一个是固定的,其余四个从分类里面取

@property (nonatomic, strong)NSMutableArray *homeClassArray;
@property (nonatomic, strong)NSMutableArray *homeClassIdArray;

//首页推荐的cell数组
@property (nonatomic, strong)NSMutableArray *cellArray;
@property (nonatomic, strong)UITextField *locationText;


@end

@implementation HomeViewController

-(void)viewDidLoad {
    [super viewDidLoad];
    
    [self homeDatasources];
    [self addlunboResources];
    [self gethomeClassdata];
    [self addHomeViewUI];
    
//    [self zhifudingdanbuttondianjishijian];
}
#warning 订单支付测试


- (void)addHomeViewUI {
    [self initSomething];
    [self addSearchView];
    [self addHomeTableview];
    [self setupHeader];
    [self setupFooter];
}

- (void)initSomething {
    self.homeClassArray = [@[]mutableCopy];
    self.homeClassIdArray = [@[]mutableCopy];
    SDCycleArray = [[NSMutableArray alloc] initWithCapacity:0];
    self.cellArray = [@[]mutableCopy];
    
}


- (void)addHomeTableview {
    self.HomeTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.firstView.frame), WEITH, HIGHT - self.tabBarController.tabBar.frame.size.height - CGRectGetHeight(self.firstView.frame)) style:UITableViewStyleGrouped];
    self.HomeTableView.dataSource = self;
    self.HomeTableView.delegate = self;
    [self.view addSubview:self.HomeTableView];
    
}

- (void)addSearchView {
    
    _locationText= [[UITextField alloc] initWithFrame:CGRectMake(0, 5*NORMHEIGHT, 90*NORMWIDTH, CGRectGetHeight(self.secondView.frame)-10*NORMHEIGHT)];
    
    _locationText.enabled = NO;
    _locationText.textColor = [UIColor whiteColor];
    _locationText.font = [UIFont systemFontOfSize:13];
    _locationText.text = @"杭州市";
    [self setLeftViewWithTextField:_locationText imageName:@"Icon_-Location-pin.png"];
    [self.secondView addSubview:_locationText];
    
    self.leftBtn.hidden = YES;
    UIButton *locationBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    locationBtn1.frame = _locationText.frame;//CGRectMake(0, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [locationBtn1 addTarget:self action:@selector(ErWeimaBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:locationBtn1];
    //    [locationBtn1 setBackgroundColor:[UIColor redColor]];
    
    
    UITextField *searchFeild = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(locationBtn1.frame) +5, 5, WEITH -(CGRectGetMaxX(self.leftBtn.frame))*2-20 , CGRectGetHeight(self.secondView.frame)-10)];
    searchFeild.placeholder = @"请输入商家或者商品名称";
    searchFeild.font = [UIFont systemFontOfSize:14];
    searchFeild.layer.cornerRadius = searchFeild.frame.size.height/2;
    searchFeild.layer.masksToBounds = YES;
    searchFeild.enabled = NO;
    searchFeild.backgroundColor = [UIColor whiteColor];
    searchFeild.layer.borderWidth = 1;
    searchFeild.layer.borderColor = [UIColor colorWithRed:52/255. green:147/255. blue:225/255. alpha:1].CGColor;
    [self setLeftViewWithTextField:searchFeild imageName:@"search-gray-icon.png"];
    [self.secondView addSubview:searchFeild];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = searchFeild.frame;
    [button addTarget:self action:@selector(searchBut) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:button];
    
}

- (void)searchBut {
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    [self presentViewController:searchVC animated:YES completion:nil];
}

//跳转到城市列表页面的点击事件
- (void)ErWeimaBtnClick:(UIButton *)button {
    //   CityListViewController *cityListVc = [[CityListViewController alloc] init];
    //  [self presentViewController:cityListVc animated:YES completion:nil];
    
    
    GPDateView * dateView = [[GPDateView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, 250*NORMHEIGHT) Data:nil];
    //    dateView.frame = CGRectMake(0, 400*NORMHEIGHT, WIDTH, 200*NORMHEIGHT);
    
    [dateView showPickerView];
    
    // _locationText
    dateView.ActionDistrictViewSelectBlock = ^(NSString *desStr,NSDictionary *selectDistrictDict){
        //   self.provinceLabel.text = [selectDistrictDict objectForKey:Key_DistrictSelectProvince];
        _locationText.text = [selectDistrictDict objectForKey:Key_DistrictSelectCity];
        //     self.areaLabel.text = [selectDistrictDict objectForKey:Key_DistrictSelectProvinceSub];
        
    };
    
}


#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    } else {
        return self.cellArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"RecomTableViewCell";
    RecomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"RecomTableViewCell" owner:nil options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    
    NSString *string = [NSString stringWithFormat:@"%@%@",  [[[[self.cellArray[indexPath.row] objectForKey:@"picprex"] objectForKey:@"s"] componentsSeparatedByString:@" "] firstObject], [self.cellArray[indexPath.row] objectForKey:@"picurl"]];
    NSLog(@"%@", string);
    [cell.recomCellImageView sd_setImageWithURL:[NSURL URLWithString:string] placeholderImage:[UIImage imageNamed:@"cellpic.png"]];
    cell.recomIntroLabel.text = [NSString stringWithFormat:@"%@", [self.cellArray[indexPath.row] objectForKey:@"title"]];
    
    cell.Pricenewlabel.text = [NSString stringWithFormat:@"会员价:%@", [self.cellArray[indexPath.row] objectForKey:@"huiyuanjia"]];
    cell.oldpriceLabel.text = [NSString stringWithFormat:@"市场价:%@", [self.cellArray[indexPath.row] objectForKey:@"shichangjia"]];
    
    //    cell.recomCellImageView.image
    //    cell.recomIntroLabel.text
    //    cell.recomAddresslabel.text
    //    cell.Pricenewlabel.text
    //    cell.oldpriceLabel.text
    
    
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
    
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 0;
    } else {
        return 80;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 140;
    } else {
        return 30;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return WEITH;
    } else {
        return 0.1;
    }
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 0) {
        if (self.homeClassArray.count!=0) {
            UIView *view = [[UIView alloc] init];
            return [self addView:view];
        } else{
            return nil;
        }
        
    } else {
        UIView *footerview = [[UIView alloc] init];
        footerview.backgroundColor = [UIColor whiteColor];
        return footerview;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ShoperDetailViewController *homecellDetail = [[ShoperDetailViewController alloc] init];
    
    homecellDetail.shopID = [NSString stringWithFormat:@"%@", [self.cellArray[indexPath.row] objectForKey:@"id"]];
    
    [self presentViewController:homecellDetail animated:YES completion:nil];
}



- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        if (SDCycleArray.count == 0) {
            [self addlunboResources];
            return nil;
        }else{
            
            // 创建不带标题的图片轮播器
            //        cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WEITH, 120) imagesGroup:SDCycleArray];
            SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WEITH, 120) imageURLsGroup:SDCycleArray];
            cycleScrollView.delegate = self;
            [self.view addSubview:cycleScrollView];
            // 轮播时间间隔，默认1.0秒，可自定义
            cycleScrollView.autoScrollTimeInterval = 2.5;
            return cycleScrollView;
        }
    }  else {
        UIView *headerView = [[UIView alloc] init];
        headerView.backgroundColor = [UIColor colorWithRed:238/255. green:238/255. blue:238/255. alpha:1];
        
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 200, 20)];
        title.text = @"精品推荐";
        [headerView addSubview:title];
        return headerView;
    }
}

- (UIView *)addView:(UIView *)view {
    NSArray *imageArray = @[[UIImage imageNamed:@"wszq-color-icon.png"],
                            [UIImage imageNamed:@"hdzx-color-icon.png"],
                            [UIImage imageNamed:@"sycz-color-icon.png"],
                            [UIImage imageNamed:@"hfcz-color-icon.png"],
                            [UIImage imageNamed:@"xxyl-color-icon.png"],
                            [UIImage imageNamed:@"msbj-color-icon.png"],
                            [UIImage imageNamed:@"jdsm-color-icon.png"],
                            [UIImage imageNamed:@"xbfs-color-icon.png"],
                            [UIImage imageNamed:@"point-gray-icon.png"]
                            ];
    
    //sycz-color-icon.png
    
    //     NSArray *titleArray = @[@"微商专区", @"鞋包服饰", @"家电数码", @"石油充值", @"活动中心", @"话费充值", @"美食保健", @"休闲娱乐", @"其他分类"];
    NSMutableArray *titleArray = [NSMutableArray arrayWithObjects:@"微商专区",  @"活动中心", @"石油充值", @"话费充值", nil];
    //    @"鞋包服饰", @"家电数码",  @"美食保健", @"休闲娱乐", @"其他分类",
    
    for (NSString *temp in self.homeClassArray) {
        [titleArray addObject:temp];
    }
    [titleArray addObject:@"其他分类"];
    
    NSInteger k = 0;
    for (NSInteger i = 0; i < 3; i++) {
        for (NSInteger j = 0; j < 3; j++) {
            ButtonView *BtnView = [[ButtonView alloc] initWithFrame:CGRectMake((WEITH/3)*j, (WEITH/3)*i, WEITH/3, WEITH/3)];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = BtnView.frame;
            [button addTarget:self action:@selector(buttonViewClick:) forControlEvents:UIControlEventTouchUpInside];
            BtnView.titleLabel.text = [NSString stringWithFormat:@"%@", titleArray[k]];
            BtnView.picImage.image = imageArray[k];
            button.tag = 600+k;
            [view addSubview:BtnView];
            [view addSubview:button];
            k++;
        }
    }
    
    return view;
}

#pragma mark --SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    NSLog(@"点击了轮播图");
}

//图片按钮的点击事件
- (void)buttonViewClick:(UIButton *)button {
    //   NSLog(@"%ld", button.tag);
    if (button.tag == 600) {
        
        DerivativeViewController *shoeVC = [[DerivativeViewController alloc] init];
        //            shoeVC.titleStr = @"微商专区";
        [self presentViewController:shoeVC animated:YES completion:nil];
    }else if (button.tag == 601){
        //活动中心
        ActivityViewController *actVc =[[ActivityViewController alloc] init];
        
        actVc.transint = 1;
        [self presentViewController:actVc animated:YES completion:nil];
    }else if (button.tag == 602){
        //石油充值
        OilChangeViewController *oilVC = [[OilChangeViewController alloc] init];
        [self presentViewController:oilVC animated:YES completion:nil];
    }else if (button.tag == 603){
        //手机充值
        MoreCreditViewController *creditVC =[[ MoreCreditViewController alloc] init];
        [self presentViewController:creditVC animated:YES completion:nil];
    }else if (button.tag == 608){
        //其他分类
        OtherClassificationViewController *otherVC = [[OtherClassificationViewController alloc] init];
        [self presentViewController:otherVC animated:YES completion:nil];
    } else {
        ShoeBagDressViewController *shoeVC = [[ShoeBagDressViewController alloc] init];
        shoeVC.titleStr = self.homeClassArray[button.tag-604];
        shoeVC.firstid = self.homeClassIdArray[button.tag-604];
        [self presentViewController:shoeVC animated:YES completion:nil];
    }
    
}

/**
 *  给UITextField设置右侧的图片
 *
 *  @param textField UITextField
 *  @param imageName 图片名称
 */

-(void)setLeftViewWithTextField:(UITextField *)textField imageName:(NSString *)imageName{
    
    UIImageView *rightView = [[UIImageView alloc]init];
    
    rightView.image = [UIImage imageNamed:imageName];
    rightView.frame = CGRectMake(0, 0, CGRectGetHeight(textField.frame), CGRectGetHeight(textField.frame));
    rightView.contentMode = UIViewContentModeCenter;
    textField.leftView = rightView;
    textField.leftViewMode = UITextFieldViewModeAlways;
}


- (void)setupHeader{
    //添加下拉刷新对象
    SDRefreshHeaderView *refreshHeader = [SDRefreshHeaderView refreshView];
    
    //     默认是在navigationController环境下，如果不是在此环境下，请设置
    refreshHeader.isEffectedByNavigationController = NO;
    
    //加入到目标tableview上
    [refreshHeader addToScrollView:self.HomeTableView];
    
    //添加下拉加载内容的方法
    __weak SDRefreshHeaderView *weakRefreshHeader = refreshHeader;
    __weak typeof(self) weakSelf = self;
    refreshHeader.beginRefreshingOperation = ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
#pragma mark -- 加载数据的方法
            [self homeDatasources];
            
            [self addlunboResources];
            [weakSelf.HomeTableView reloadData];
            [weakRefreshHeader endRefreshing];
        });
    };
    
    // 进入页面自动加载一次数据
    [refreshHeader autoRefreshWhenViewDidAppear];
}

- (void)setupFooter{
    SDRefreshFooterView *refreshFooter = [SDRefreshFooterView refreshView];
    refreshFooter.isEffectedByNavigationController = NO;
    [refreshFooter addToScrollView:self.HomeTableView];
    [refreshFooter addTarget:self refreshAction:@selector(footerRefresh)];
    _refreshFooter = refreshFooter;
}


- (void)footerRefresh{
    
    __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
#pragma mark -- 加载数据的方法
        
        [weakSelf homeDatasources];
        
        [weakSelf addlunboResources];
        [weakSelf.HomeTableView reloadData];
        [weakSelf.refreshFooter endRefreshing];
    });
}

//首页精品推荐
- (void)homeDatasources {
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    
    NSString *ajax = @"1";
    NSString *fffid = @"991";
    //
    NSDictionary *param = @{@"ajax":[NSString stringWithFormat:@"%@", ajax], @"fffid":[NSString stringWithFormat:@"%@", fffid]};
    
    
    [mgr POST:@"http://www.ylgw8.com/Prolist/index" parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *string = [self toArrayOrNSDictionary:responseObject];
        
        //NSData数据转化成NSArray
        self.cellArray  = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        
        
        [self.HomeTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
     {
         //         operation.response.statusCode;//404 401之类
         NSLog(@"数据请求错误原因:%@", error);
         NSLog(@"数据请求错误码:%ld", (long)operation.response.statusCode);
     }];
}



- (void)addlunboResources{
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    __weak HomeViewController *homeself = self;
    [mgr GET:@"http://www.ylgw8.com/AppBan/startPic" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSArray *array = [homeself toArrayOrNSDictionary:responseObject];
        //清空数组,放置重复添加
        SDCycleArray = [@[]mutableCopy];
        
        for (NSString *temStra in array) {
            [SDCycleArray addObject:[NSURL URLWithString:temStra]];
        }
        
        [homeself.HomeTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}

- (void)gethomeClassdata{
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    __weak HomeViewController *homeself = self;
    [mgr GET:@"http://ylgw8.com/Prolist/getClass" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSArray *array = [homeself toArrayOrNSDictionary:responseObject];
        
        for (NSInteger i=0; i<array.count; i++) {
            if (i<4) {
                [self.homeClassArray addObject:[array[i] objectForKey:@"classname"]];
                [self.homeClassIdArray addObject:[NSString stringWithFormat:@"%@", [array[i] objectForKey:@"id"]]];
            }
        }
        
        [homeself.HomeTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}


// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}
@end
